package deviceinfo.wsm.com.deviceinfo;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.CountDownTimer;
import android.os.Handler;
import android.support.annotation.NonNull;

import com.google.gson.Gson;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;

import deviceinfo.wsm.com.deviceinfo.app.AppInfoUtils;
import deviceinfo.wsm.com.deviceinfo.common.Md5Encoder;
import deviceinfo.wsm.com.deviceinfo.contact.ContactsInfoUtils;
import deviceinfo.wsm.com.deviceinfo.cpu.CPUInfoUtils;
import deviceinfo.wsm.com.deviceinfo.device.DeviceInfoUtils;
import deviceinfo.wsm.com.deviceinfo.hardware.HardwareInfoUtils;
import deviceinfo.wsm.com.deviceinfo.installpackage.InstallPackageInfoUtils;
import deviceinfo.wsm.com.deviceinfo.location.LocationInfoUtils;
import deviceinfo.wsm.com.deviceinfo.net.NetInfoUtils;
import deviceinfo.wsm.com.deviceinfo.plugin.com.an.deviceinfo.usercontacts.UserContacts;
import deviceinfo.wsm.com.deviceinfo.sdcard.SDCardInfoUtils;
import deviceinfo.wsm.com.deviceinfo.upload.HttpClient;
import deviceinfo.wsm.com.deviceinfo.upload.NetWorkInterfaces;
import deviceinfo.wsm.com.deviceinfo.upload.request.CusRequestBody;
import deviceinfo.wsm.com.deviceinfo.upload.request.CusRequestEventBody;
import deviceinfo.wsm.com.deviceinfo.upload.request.SensorBean;
import deviceinfo.wsm.com.deviceinfo.upload.response.BaseResponse;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by 王家宝 on 2018/7/5.
 * TEL:18241150668
 * MAIL:639586819@qq.com
 */

public class WsmDeviceInfoSDK {

    public static final String EVENT_SP_KEY = "event_sp_key";

    private static LinkedHashMap<String, String> locationInfo;
    private static LinkedHashMap<String, String> netInfo;
    private static LinkedHashMap<String, List> contactsInfo;
    private static LinkedHashMap<String, String> appInfo;
    private static LinkedHashMap<String, String> deviceInfo;
    private static LinkedHashMap<String, String> packageInfo;
    static LinkedHashMap<String, ArrayList<LinkedHashMap>> sensorInfo = new LinkedHashMap<>();
    private static LinkedHashMap<String, String> memoryInfo;
    private static LinkedHashMap<String, String> cpuInfo;
    private static String tokenKey = "97d7b579-9173-11e8-9a60-000c291fbd11";

    public WsmDeviceInfoSDK() {

    }

    private static final String[] PERMISSION = new String[]{
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.READ_PHONE_STATE,
            Manifest.permission.READ_CONTACTS,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE
    };


    @SuppressLint("StaticFieldLeak")
    private static WsmSDK wsmSDK;

//    @SuppressLint("StaticFieldLeak")
//    private static PermissionManager permissionManager;

    public static void initSDK(Context context) {
        wsmSDK = new WsmSDK(context);
        getPermission();

        SharedPreferences sharedPreferences = context.getSharedPreferences(context.getPackageName() + "WsmTec", Context.MODE_PRIVATE);
        Set<String> eventList = sharedPreferences.getStringSet(EVENT_SP_KEY, null);
        if (eventList == null) {
            SharedPreferences.Editor editor = sharedPreferences.edit();
            Set<String> list = new TreeSet<>();
            editor.putStringSet(EVENT_SP_KEY, list);
            editor.apply();
        }

        CountDownTimer timer = new CountDownTimer(Long.MAX_VALUE, 300000) {
            @Override
            public void onTick(long millisUntilFinished) {
                uploadEvent2Server();
            }

            @Override
            public void onFinish() {

            }
        }.start();

    }


    private static void getPermission() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    netInfo = DeviceInfoUtil.getNetInfo();
                    contactsInfo = DeviceInfoUtil.getContactsInfo();
                    locationInfo = DeviceInfoUtil.getLocationInfo();

                    appInfo = DeviceInfoUtil.getAppInfo();
                    deviceInfo = DeviceInfoUtil.getDeviceInfo();
                    packageInfo = DeviceInfoUtil.getInstallPackageInfo();
                    memoryInfo = DeviceInfoUtil.getMemoryInfo();

                    cpuInfo = DeviceInfoUtil.getCPUInfo();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();

        DeviceInfoUtil.getSensorInfo();
        runUpload();

    }

    private static void runUpload() {
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                uploadInfo2Server();
            }
        }, 10000);
    }

    public static WsmSDK getWsmSDK() {
        return wsmSDK;
    }

    static LinkedHashMap<String, String> getCpuInfo() {
        return CPUInfoUtils.getAll();
    }

    static LinkedHashMap<String, String> getRomInfo() {
        return SDCardInfoUtils.getAll();
    }


    static void startHardwareMonitor(final OnHardwareDataBackListener onHardwareDataBackListener) {
        HardwareInfoUtils.InitAccelerometerMoniter(onHardwareDataBackListener);
    }

    static LinkedHashMap<String, String> getLocationInfo() {
        return LocationInfoUtils.getAll();
    }

    static LinkedHashMap<String, String> getAppInfo() {
        return AppInfoUtils.getAll();
    }

    static LinkedHashMap<String, String> getDeviceInfo() {
        return DeviceInfoUtils.getAll();
    }

    static LinkedHashMap<String, String> getNetInfo() {
        return NetInfoUtils.getAll();
    }

    static LinkedHashMap<String, String> getInstallPackageInfo() {
        return InstallPackageInfoUtils.getAll();
    }

    static LinkedHashMap<String, List> getContactsInfo() {
        return ContactsInfoUtils.getAll();
    }


    public interface OnHardwareDataBackListener {
        void onSuccess(ArrayList<LinkedHashMap> sensorResult, ArrayList<LinkedHashMap> gravitySensorResult, ArrayList<LinkedHashMap> gyroscopeSensorResult);

        void onFailed();
    }

    private synchronized static void uploadEvent2Server() {

        SharedPreferences sharedPreferences = WsmDeviceInfoSDK.getWsmSDK().
                getAppContext().getSharedPreferences(WsmDeviceInfoSDK.getWsmSDK().
                getAppContext().getPackageName() + "WsmTec", Context.MODE_PRIVATE);
        Set<String> data = sharedPreferences.getStringSet(EVENT_SP_KEY, null);
        if (data != null) {
            CusRequestEventBody body = new CusRequestEventBody();
            try {
                int tel = Integer.valueOf(netInfo.get("sim卡手机号"));
                body.setPhoneNo(tel);
            } catch (Exception e) {
                body.setPhoneNo(0);
            }

            body.setOriginType("android");
            body.setDataType("useraction");
            try {
                body.setDeviceId(netInfo.get("IMEI"));
            } catch (Exception e) {
                body.setDeviceId("0000000000000000");
            }
            body.setSmartId(DeviceInfoUtils.getUniquePsuedoID());

            CusRequestEventBody.DataBean dataBean = new CusRequestEventBody.DataBean();

            ArrayList<CusRequestEventBody.DataBean.UserActionBean> tempList = new ArrayList<>();
            for (String o : data) {
                tempList.add(new Gson().fromJson(o, CusRequestEventBody.DataBean.UserActionBean.class));
            }

            dataBean.setUserAction(tempList);

            body.setData(dataBean);

            long time = System.currentTimeMillis();
            body.setUploadTime(time + "");
            body.setSign(Md5Encoder.getMd5Value(tokenKey + "_" + time));

            Call<BaseResponse> call = HttpClient.getService(NetWorkInterfaces.class).uploadUserEvent(body);
            call.enqueue(new Callback<BaseResponse>() {
                @Override
                public void onResponse(Call<BaseResponse> call, Response<BaseResponse> response) {
                    try {
                        if ("success".equals(response.body().getResult())) {
                            SharedPreferences sharedPreferences = WsmDeviceInfoSDK.getWsmSDK().
                                    getAppContext().getSharedPreferences(WsmDeviceInfoSDK.getWsmSDK().
                                    getAppContext().getPackageName() + "WsmTec", Context.MODE_PRIVATE);
                            Set<String> eventList = sharedPreferences.getStringSet(WsmDeviceInfoSDK.EVENT_SP_KEY, null);
                            if (eventList != null) {
                                eventList.clear();
                                SharedPreferences.Editor editor = sharedPreferences.edit();
                                editor.putStringSet(WsmDeviceInfoSDK.EVENT_SP_KEY, eventList);
                                editor.apply();
                            } else {
                                eventList = new TreeSet<>();
                                SharedPreferences.Editor editor = sharedPreferences.edit();
                                editor.putStringSet(WsmDeviceInfoSDK.EVENT_SP_KEY, eventList);
                                editor.apply();
                            }
                        }

                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

                @Override
                public void onFailure(Call<BaseResponse> call, Throwable t) {
                }
            });
        }


    }

    private static void uploadInfo2Server() {

        final CusRequestBody body = new CusRequestBody();
        try {
            int tel = Integer.valueOf(netInfo.get("sim卡手机号"));
            body.setPhoneNo(tel);
        } catch (Exception e) {
            body.setPhoneNo(0);
        }
        try {
            body.setDeviceId(netInfo.get("IMEI"));
        } catch (Exception e) {
            e.printStackTrace();
        }
        body.setSmartId(DeviceInfoUtils.getUniquePsuedoID());
        body.setOriginType("android");
        body.setDataType("equipment");
        String uploadTime = System.currentTimeMillis() + "";
        body.setUploadTime(uploadTime);
        body.setSign(Md5Encoder.getMd5Value(tokenKey + "_" + uploadTime));
        CusRequestBody.DataBean data = new CusRequestBody.DataBean();

        try {
            data.setCpuInfo(makeCpuInfo());
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            data.setInstalledPackage(packageInfo.get("已安装应用"));
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            data.setDiskInfo(makeDiskInfo());
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            data.setMemoryInfo(makeMemoryInfo());
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            data.setSystemInfo(makeSystemInfo());
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            data.setAppinfo(makeAppInfo());
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            data.setAddressBookList(makeContactsInfo());
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            data.setRoganInfo(makeRoganInfo());
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            data.setNetworkInfo(makeNetInfo());
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            data.setGps(locationInfo.get("混合经纬度"));
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            data.setIsAgency(netInfo.get("是否代理"));
        } catch (Exception e) {
            e.printStackTrace();
        }

        body.setData(data);

        new Thread(new Runnable() {
            @Override
            public void run() {
                Call<BaseResponse> call = HttpClient.getService(NetWorkInterfaces.class)
                        .uploadDeviceInfo(body);
                call.enqueue(new Callback<BaseResponse>() {
                    @Override
                    public void onResponse(Call<BaseResponse> call, Response<BaseResponse> response) {
                    }

                    @Override
                    public void onFailure(Call<BaseResponse> call, Throwable t) {
                    }
                });
            }
        }).start();


    }

    @NonNull
    private static CusRequestBody.DataBean.NetworkInfoBean makeNetInfo() {
        CusRequestBody.DataBean.NetworkInfoBean bean = new CusRequestBody.DataBean.NetworkInfoBean();
        bean.setCellIp(netInfo.get("IP"));
        bean.setIsConnWifi(netInfo.get("WifiEnabled"));
        bean.setInternetType(netInfo.get("NetworkType"));
        bean.setCarrierMobileCountryCode(netInfo.get("sim卡国家码"));
        bean.setCarrierOperator(netInfo.get("sim卡运营商名称"));
        return bean;
    }

    @NonNull
    private static CusRequestBody.DataBean.RoganInfoBean makeRoganInfo() {
        CusRequestBody.DataBean.RoganInfoBean roganInfoBean = new CusRequestBody.DataBean.RoganInfoBean();
        roganInfoBean.setAccelerometerSersorInfo(makeSensorInfo1());
        roganInfoBean.setGravitySersorInfo(makeSensorInfo2());
        roganInfoBean.setGyroSersorInfo(makeSensorInfo3());
        return roganInfoBean;
    }

    @NonNull
    private static CusRequestBody.DataBean.CpuInfoBean makeCpuInfo() {
        CusRequestBody.DataBean.CpuInfoBean infoBean = new CusRequestBody.DataBean.CpuInfoBean();
        try {
            infoBean.setCpuArchitecture(cpuInfo.get("cpu名称"));
            infoBean.setCpuProcessorNum(cpuInfo.get("cpu核心数"));
            infoBean.setCpuSerial(cpuInfo.get("cpu序列号"));
            return infoBean;
        } catch (Exception e) {
            return infoBean;
        }

    }

    @NonNull
    private static CusRequestBody.DataBean.DiskInfoBean makeDiskInfo() {
        CusRequestBody.DataBean.DiskInfoBean infoBean = new CusRequestBody.DataBean.DiskInfoBean();
        infoBean.setDiskFreeSpace(memoryInfo.get("rom可用大小"));
        infoBean.setDiskTotalSpace(memoryInfo.get("rom总大小"));
        infoBean.setDiskUsedSpace(memoryInfo.get("rom已用大小"));
        return infoBean;
    }

    @NonNull
    private static CusRequestBody.DataBean.MemoryInfoBean makeMemoryInfo() {
        CusRequestBody.DataBean.MemoryInfoBean infoBean = new CusRequestBody.DataBean.MemoryInfoBean();
        infoBean.setMemoryTotal(memoryInfo.get("内存总大小"));
        infoBean.setMemoryUsed(memoryInfo.get("内存已使用"));
        return infoBean;
    }


    @NonNull
    private static CusRequestBody.DataBean.SystemInfoBean makeSystemInfo() {
        CusRequestBody.DataBean.SystemInfoBean infoBean = new CusRequestBody.DataBean.SystemInfoBean();
        infoBean.setSystemUpTime(deviceInfo.get("开机时间"));
        infoBean.setDeviceType(deviceInfo.get("Model"));
        infoBean.setDeviceName(deviceInfo.get("BuildBrand"));
        infoBean.setDeviceModel(deviceInfo.get("Product"));
        infoBean.setOs("Android");
        infoBean.setOsVersion(deviceInfo.get("OsVersion"));
        infoBean.setIsEmulate(deviceInfo.get("是否是模拟器"));
        infoBean.setResolution(deviceInfo.get("屏幕分辨率"));
        infoBean.setScreenW(deviceInfo.get("屏幕宽度"));
        infoBean.setScreenH(deviceInfo.get("屏幕高度"));
        infoBean.setScreenBrightness(deviceInfo.get("屏幕亮度"));
        infoBean.setIsJailBreak(deviceInfo.get("是否root"));
        infoBean.setCarrierAllowVoip("");
        infoBean.setIsOpenGPS(deviceInfo.get("GPS是否开启"));
        infoBean.setGatherDate(System.currentTimeMillis() + "");
        return infoBean;
    }


    @NonNull
    private static CusRequestBody.DataBean.AppinfoBean makeAppInfo() {
        CusRequestBody.DataBean.AppinfoBean infoBean = new CusRequestBody.DataBean.AppinfoBean();
        infoBean.setAppName(appInfo.get("应用名称"));
        infoBean.setAppPackageName(appInfo.get("应用包名"));
        infoBean.setAppVersion(appInfo.get("应用版本号"));
        infoBean.setAppVersionCode(appInfo.get("应用版本编号"));
        return infoBean;
    }

    @NonNull
    private static ArrayList<CusRequestBody.DataBean.AddressBookListBean> makeContactsInfo() {
        ArrayList<CusRequestBody.DataBean.AddressBookListBean> contactsList = new ArrayList<>();
        List<UserContacts> contactList = contactsInfo.get("联系人信息");
        if (contactList != null && contactList.size() != 0) {
            for (int i = 0; i < contactList.size(); i++) {
                CusRequestBody.DataBean.AddressBookListBean bookListBean = new CusRequestBody.DataBean.AddressBookListBean();
                bookListBean.setNickname(contactList.get(i).getDisplayName());
                bookListBean.setTelNo(contactList.get(i).getMobileNumber());
                contactsList.add(bookListBean);
            }
            return contactsList;
        } else {
            return new ArrayList<>();
        }
    }


    @NonNull
    private static ArrayList<SensorBean> makeSensorInfo1() {
        ArrayList<SensorBean> accelerometerSersorInfo = new ArrayList<>();
        if (sensorInfo != null) {
            for (int i = 0; i < sensorInfo.size(); i++) {
                ArrayList<LinkedHashMap> data = sensorInfo.get("加速度计");
                if (data != null && data.size() != 0) {
                    SensorBean sensorBean = new SensorBean();
                    try {
                        sensorBean.setX((float) data.get(i).get("x"));
                        sensorBean.setY((float) data.get(i).get("y"));
                        sensorBean.setZ((float) data.get(i).get("z"));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    accelerometerSersorInfo.add(sensorBean);
                }
            }
            return accelerometerSersorInfo;
        } else {
            return accelerometerSersorInfo;
        }


    }

    @NonNull
    private static ArrayList<SensorBean> makeSensorInfo2() {
        ArrayList<SensorBean> accelerometerSersorInfo = new ArrayList<>();
        if (sensorInfo != null) {
            for (int i = 0; i < sensorInfo.size(); i++) {
                ArrayList<LinkedHashMap> data = sensorInfo.get("重力计");
                if (data != null && data.size() != 0) {
                    SensorBean sensorBean = new SensorBean();
                    try {
                        sensorBean.setX((float) data.get(i).get("x"));
                        sensorBean.setY((float) data.get(i).get("y"));
                        sensorBean.setZ((float) data.get(i).get("z"));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    accelerometerSersorInfo.add(sensorBean);
                }
            }
            return accelerometerSersorInfo;
        } else {
            return accelerometerSersorInfo;
        }

    }

    @NonNull
    private static ArrayList<SensorBean> makeSensorInfo3() {
        ArrayList<SensorBean> accelerometerSersorInfo = new ArrayList<>();
        if (sensorInfo != null) {
            for (int i = 0; i < sensorInfo.size(); i++) {
                ArrayList<LinkedHashMap> data = sensorInfo.get("陀螺仪");
                if (data != null && data.size() != 0) {
                    SensorBean sensorBean = new SensorBean();
                    try {
                        sensorBean.setX((float) data.get(i).get("x"));
                        sensorBean.setY((float) data.get(i).get("y"));
                        sensorBean.setZ((float) data.get(i).get("z"));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    accelerometerSersorInfo.add(sensorBean);
                }
            }
            return accelerometerSersorInfo;
        } else {
            return accelerometerSersorInfo;
        }


    }


}
